package com.wgts.wgts.mvp.view.activity.affrimorder;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseActivity;
import com.wgts.wgts.control.dialog.PlatformPayData;
import com.wgts.wgts.control.dialog.PlatformPayDialogFragment;
import com.wgts.wgts.control.dialog.ToastDate;
import com.wgts.wgts.control.dialog.ToastDialogFragment;
import com.wgts.wgts.control.recycleview.CustomLineaLayoutManager;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerAffirmOrderActivityComponent;
import com.wgts.wgts.dagger.module.AffirmOrderActivityModule;
import com.wgts.wgts.localbean.PayData;
import com.wgts.wgts.mvp.presenter.IAffirmOrderActivityPresenter;
import com.wgts.wgts.mvp.view.IAffirmOrderActivityView;
import com.wgts.wgts.mvp.view.activity.mycenter.ShippingAddressActivity;
import com.wgts.wgts.mvp.view.activity.pay.ContinuePayActivity;
import com.wgts.wgts.mvp.view.activity.pay.PaySuccessActivity;
import com.wgts.wgts.mvp.view.activity.setPassWord.SettingPasswordActivity;
import com.wgts.wgts.mvp.view.activity.shopkeeper.AdvancedTaskActivity;
import com.wgts.wgts.mvp.view.activity.shopkeeper.UpgradeShopKeeperActivity;
import com.wgts.wgts.netmodle.req.AffirmOrderRequest;
import com.wgts.wgts.netmodle.req.OrderLeaveMessage;
import com.wgts.wgts.netmodle.resp.AffirmOrderEntity;
import com.wgts.wgts.netmodle.resp.OrderEntity;
import com.wgts.wgts.netmodle.resp.ShippingAddressEntity;
import com.wgts.wgts.thirdParty.pay.PayTools;
import com.wgts.wgts.tools.AppInfor;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
 *
 *
 *   data:2018/9/715:43
 *
 */public class AffirmOrderActivity extends BaseActivity implements IAffirmOrderActivityView {
    @BindView(R.id.back_btn_image)
    ImageView backBtnImage;
    @BindView(R.id.back_btn_ly)
    LinearLayout backBtnLy;
    @BindView(R.id.include_title)
    TextView includeTitle;
    @BindView(R.id.include_text)
    TextView includeText;
    @BindView(R.id.include_right_ly)
    LinearLayout includeRightLy;
    @BindView(R.id.affirm_location_image)
    ImageView affirmLocationImage;
    @BindView(R.id.affirm_user_name)
    TextView affirmUserName;
    @BindView(R.id.affirm_user_phone)
    TextView affirmUserPhone;
    @BindView(R.id.affirm_user_location)
    TextView affirmUserLocation;
    @BindView(R.id.affirm_choose_location)
    LinearLayout affirmChooseLocation;
    @BindView(R.id.affirm_order_recycle)
    RecyclerView affirmOrderRecycle;
    @BindView(R.id.affirm_order_shopping_number)
    TextView affirmOrderShoppingNumber;
    @BindView(R.id.affirm_order_shopping_all_price)
    TextView affirmOrderShoppingAllPrice;
    @BindView(R.id.affirm_order_shopping_freight)
    TextView affirmOrderShoppingFreight;
    @BindView(R.id.affirm_order_all_price)
    TextView affirmOrderAllPrice;
    @BindView(R.id.affirm_order_need_pay_price)
    TextView affirmOrderNeedPayPrice;
    @BindView(R.id.wx_pay_image)
    ImageView wxPayImage;
    @BindView(R.id.wx_pay_ly)
    LinearLayout wxPayLy;
    @BindView(R.id.alipay_pay_image)
    ImageView alipayPayImage;
    @BindView(R.id.alipay_pay_ly)
    LinearLayout alipayPayLy;
    @BindView(R.id.affirm_order_residue_money)
    TextView affirmOrderResidueMoney;
    @BindView(R.id.mohu_pay_image)
    ImageView mohuPayImage;
    @BindView(R.id.mohu_pay_ly)
    LinearLayout mohuPayLy;
    @BindView(R.id.affirm_order_go_pay_price)
    TextView affirmOrderGoPayPrice;
    @BindView(R.id.affirm_order_go_pay_button)
    LinearLayout affirmOrderGoPayButton;
    @BindView(R.id.include_right_image)
    ImageView includeRightImage;
    @BindView(R.id.choose_adress_ly)
    LinearLayout chooseAdressLy;
    @BindView(R.id.show_adress_ly)
    LinearLayout showAdressLy;
    @BindView(R.id.show_or_hidden_text)
    TextView showOrHiddenText;
    @BindView(R.id.show_or_hidden_image)
    ImageView showOrHiddenImage;
    @BindView(R.id.show_or_hidden_recycle)
    LinearLayout showOrHiddenRecycle;
    @BindView(R.id.preferential_price_text)
    TextView preferentialPriceText;
    @BindView(R.id.shop_store_plane_text)
    TextView shopStorePlaneText;
    @BindView(R.id.up_level_ly)
    LinearLayout upLevelLy;
    @BindView(R.id.shop_car_up_level)
    LinearLayout shopCarUpLevel;
    @BindView(R.id.parent_ly)
    FrameLayout parentLy;
    @BindView(R.id.placeholder_click)
    LinearLayout placeholderClick;
    @BindView(R.id.up_level_text)
    TextView upLevelText;
    //支付方式0微信，1支付宝，2
    private Integer choosePay = 1;
    private String payType = "ALIPAY";
    private AffirmOrderParentAdapter affirmOrderAdapter;

    private List<OrderLeaveMessage> orderLeaveMessages;
    List<AffirmOrderEntity.shop> shopList;

    private CustomLineaLayoutManager lineaLayoutManager;
    //购物车id
    private ArrayList<Integer> arrayList;
    private boolean showAll = false;
    private PlatformPayData data;
    //余额及支付金额
    private String SplatformCoin, SneedPayPrice;
    //上级页面获取的商品数据
    private AffirmOrderRequest request;
    private int AddressResult = 1;
    //选则收货地址数据
    private ShippingAddressEntity resultEntity;
    //收货地址ID
    private String AddressId;
    public static final String cartIdData = "cartIds";
    public static final String Products = "products";
    //是否是会员订单
    private String orderType;
    //佣金奖励
    private String commissionProfit;
    private PayData payData;


    @Inject
    IAffirmOrderActivityPresenter presenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_affirm_order);
        ButterKnife.bind(this);
        includeTitle.setText("确认订单");
        alipayPayImage.setSelected(true);
        request = new AffirmOrderRequest();
        Intent intent = getIntent();
        request = intent.getParcelableExtra(Products);
        arrayList = intent.getIntegerArrayListExtra(cartIdData);
        initView();
    }

    @Override
    public void init() {
        DaggerAffirmOrderActivityComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .affirmOrderActivityModule(new AffirmOrderActivityModule(this))
                .build()
                .inject(this);
        shopList = new ArrayList<>();
    }

    private void initView() {
        showDialog();
        lineaLayoutManager = new CustomLineaLayoutManager(this);
        lineaLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        lineaLayoutManager.setScrollEnabled(false);
        affirmOrderRecycle.setLayoutManager(lineaLayoutManager);
        presenter.affirmOrderResult(request);
        affirmOrderAdapter = new AffirmOrderParentAdapter(this, shopList);
        affirmOrderRecycle.setAdapter(affirmOrderAdapter);
    }

    @OnClick({R.id.back_btn_ly, R.id.affirm_choose_location, R.id.wx_pay_ly, R.id.alipay_pay_ly,
            R.id.mohu_pay_ly, R.id.affirm_order_go_pay_button, R.id.choose_adress_ly, R.id.show_or_hidden_recycle,
            R.id.shop_car_up_level, R.id.placeholder_click})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn_ly:
                finish();
                break;
            case R.id.affirm_choose_location:
                Intent intent = new Intent(AffirmOrderActivity.this, ShippingAddressActivity.class);
                intent.putExtra(ShippingAddressActivity.AFFIRM_ORDER_ADDRESS_RESULT, "affirmOrderAddressResult");
                startActivityForResult(intent, AddressResult);
                break;
            case R.id.wx_pay_ly:
                choosePayType(0);
                break;
            case R.id.alipay_pay_ly:
                choosePayType(1);
                break;
            case R.id.mohu_pay_ly:
                choosePayType(2);
                break;
            case R.id.affirm_order_go_pay_button:
                if (AddressId.equals("") || AddressId == null || AddressId.equals("0")) {
                    MoHuToast.showToast("请选择收货地址");
                    return;
                }
                orderLeaveMessages = new ArrayList<>();
                for (int i = 0; i < shopList.size(); i++) {
                    OrderLeaveMessage message = new OrderLeaveMessage();
                    message.sellerId = 0;
                    if (shopList.get(i).getOrderLeaveMessage() == null) {
                        message.leaveMessage = "";
                    } else {
                        message.leaveMessage = shopList.get(i).getOrderLeaveMessage();
                    }
                    orderLeaveMessages.add(message);
                }
                if (choosePay == 2) {
                    if (AppInfor.getInstance().isModifyPayPassword()){
                        platformPay();
                    }else {
                        settingPassword();
                    }
                } else {
                    showDialog();
                    presenter.placeOrder(request, AddressId, payType, "", arrayList, orderLeaveMessages);
                }
                break;
            case R.id.choose_adress_ly:
                Intent intent1 = new Intent(AffirmOrderActivity.this, ShippingAddressActivity.class);
                intent1.putExtra(ShippingAddressActivity.AFFIRM_ORDER_ADDRESS_RESULT, "affirmOrderAddressResult");
                startActivityForResult(intent1, AddressResult);
                break;
            case R.id.show_or_hidden_recycle:
                if (showAll) {
                    showAll = false;
                    presenter.getShopList(showAll);
                    showOrHiddenText.setText("展开全部商品");
                    showOrHiddenImage.setImageResource(R.mipmap.ic_public_load);
                } else {
                    showAll = true;
                    presenter.getShopList(showAll);
                    showOrHiddenText.setText("收起全部商品");
                    showOrHiddenImage.setImageResource(R.mipmap.ic_public_up);
                }
                break;
            case R.id.shop_car_up_level:
                if (AppInfor.getInstance().getUserState() < 2) {
                    intent = new Intent(AffirmOrderActivity.this, UpgradeShopKeeperActivity.class);
                } else {
                    intent = new Intent(AffirmOrderActivity.this, AdvancedTaskActivity.class);
                }
                startActivity(intent);
                break;
            case R.id.placeholder_click:
                //空方法
                break;
        }
    }

    /*
     * 选择支付方式
     * */
    private void choosePayType(Integer type) {
        switch (type) {
            case 0:
                choosePay = 0;
                payType = "WXPAY";
                wxPayImage.setSelected(true);
                alipayPayImage.setSelected(false);
                mohuPayImage.setSelected(false);
                break;
            case 1:
                choosePay = 1;
                payType = "ALIPAY";
                wxPayImage.setSelected(false);
                alipayPayImage.setSelected(true);
                mohuPayImage.setSelected(false);
                break;
            case 2:
                choosePay = 2;
                payType = "BALANCEPAY";
                wxPayImage.setSelected(false);
                alipayPayImage.setSelected(false);
                mohuPayImage.setSelected(true);
                break;
            default:
        }
    }

    //支付方式
    private void platformPay() {
        data = new PlatformPayData();
        //data.setOrderInfo("订单信息，支付业务安全信息");
        data.setPayPrice(SneedPayPrice);
        data.setResidueCoin("账户余额：" + SplatformCoin + "元");
        PlatformPayDialogFragment dialogFragment = PlatformPayDialogFragment.getPlatformPayDialogFragment(data);
        dialogFragment.show(getSupportFragmentManager(), "platformPayDialog");
        dialogFragment.setPlatformPay(new PlatformPayDialogFragment.platformPay() {
            @Override
            public void platformPay(String password) {
                showDialog();
                presenter.placeOrder(request, AddressId, payType, password, arrayList, orderLeaveMessages);
            }
        });


    }
    //设置支付密码
    private void settingPassword(){
        ToastDate toastDate = new ToastDate();
        toastDate.setCancelQuestion("请先设置资金密码");
        toastDate.setCancelText("取消");
        toastDate.setPointText("去设置");
        final ToastDialogFragment fragment = ToastDialogFragment.setToastMessage(toastDate);
        fragment.show(getSupportFragmentManager(), "SettingPasswordDialog");
        fragment.setOnClickListener(new ToastDialogFragment.OnClickListener() {
            @Override
            public void onClickCancle() {
                Intent intent = new Intent(AffirmOrderActivity.this, SettingPasswordActivity.class);
                startActivity(intent);
                fragment.dismiss();
            }

            @Override
            public void onClickEnsuer() {
                fragment.dismiss();
            }
        });
    }

    @Override
    public void onError(int status, String msg) {
        dialogDismiss();
        MoHuToast.showToast(msg);
    }

    @Override
    public void affirmOrderResult(AffirmOrderEntity entity) {
        dialogDismiss();
        parentLy.setVisibility(View.VISIBLE);
        /*
        * 去升级状态取消
        * */
//        if (entity.orderType.equals("VIP_ORDER")){
//            shopCarUpLevel.setVisibility(View.GONE);
//            shopCarUpLevel.setClickable(false);
//        }else {
//            if (AppInfor.getInstance().getUserState() > 3) {
//                upLevelLy.setVisibility(View.GONE);
//                shopCarUpLevel.setClickable(false);
//            } else if (AppInfor.getInstance().getUserState() < 2) {
//                upLevelLy.setVisibility(View.VISIBLE);
//                shopCarUpLevel.setClickable(true);
//                upLevelText.setText("去升级");
//            } else {
//                upLevelLy.setVisibility(View.VISIBLE);
//                shopCarUpLevel.setClickable(true);
//                upLevelText.setText("去升级");
//            }
//        }
        if (entity.shops.get(0).products.size() < 2) {
            showOrHiddenRecycle.setVisibility(View.GONE);
        } else {
            showOrHiddenRecycle.setVisibility(View.VISIBLE);
        }
        if (entity.addressId == null || entity.addressId.equals("") || entity.addressId.equals("0")) {
            chooseAdressLy.setVisibility(View.VISIBLE);
            showAdressLy.setVisibility(View.GONE);
        } else {
            chooseAdressLy.setVisibility(View.GONE);
            showAdressLy.setVisibility(View.VISIBLE);
            affirmUserName.setText(entity.userName);
            affirmUserPhone.setText(entity.userPhone);
            affirmUserLocation.setText(entity.province + " " + entity.city + " " + entity.area
                    + " " + entity.details);
        }
        commissionProfit = entity.orderCommissionProfit;
        orderType = entity.orderType;
        AddressId = entity.addressId;
        affirmOrderShoppingNumber.setText(entity.productCount + "件");
        affirmOrderShoppingAllPrice.setText("+" + entity.orderPrice + "元");
        affirmOrderShoppingFreight.setText("+" + entity.orderSendPrice + "元");
        preferentialPriceText.setText("-" + entity.orderDiscountPrice + "元");
        affirmOrderAllPrice.setText(entity.orderTruePrice);
        shopStorePlaneText.setText(entity.orderDisCountTip);
        SneedPayPrice = entity.orderTruePrice;
        SplatformCoin = entity.availableBalance;
        affirmOrderGoPayPrice.setText("￥" + entity.orderTruePrice);
        affirmOrderResidueMoney.setText("账户余额：￥" + entity.availableBalance);
        Double needPayPrice = Double.parseDouble(entity.orderTruePrice);
        Double platformCoin = Double.parseDouble(entity.availableBalance);
        if (platformCoin < needPayPrice) {
            mohuPayImage.setImageResource(R.mipmap.no_pay_check);
            mohuPayLy.setClickable(false);
        } else {
            mohuPayImage.setImageResource(R.drawable.pay_check);
            mohuPayLy.setClickable(true);
        }
        presenter.getShopList(showAll);
    }

    @Override
    public void getShopList(List<AffirmOrderEntity.shop> shops) {
        shopList.clear();
        shopList.addAll(shops);
        affirmOrderAdapter.notifyDataSetChanged();
    }

    @Override
    public void placeOrder(String payType, OrderEntity orderEntity) {
        dialogDismiss();
        payData = new PayData();
        payData.commissionProfit = commissionProfit;
        payData.orderId = orderEntity.orderId;
        payData.orderCode = orderEntity.orderCode;
        payData.needPayPrice = SneedPayPrice;
        payData.orderType = orderType;
        payData.platformCoin = SplatformCoin;
        switch (payType) {
            case "WXPAY":
                PayTools.getInstance().pay(0, orderEntity.orderPayParam, this, payData);
                break;
            case "ALIPAY":
                PayTools.getInstance().pay(1, orderEntity.orderPayParam, this, payData);
                break;
            case "BALANCEPAY":
                Intent intent = new Intent(AffirmOrderActivity.this, PaySuccessActivity.class);
                intent.putExtra(PayTools.PAY_DATE, payData);
                startActivity(intent);
                Intent intent1 = new Intent();
                intent.putExtra("PayStatue", "success");
                setResult(ContinuePayActivity.PAY_RESULT_OK, intent1);
                finish();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AddressResult && data != null) {
            resultEntity = data.getParcelableExtra("address");
            chooseAdressLy.setVisibility(View.GONE);
            showAdressLy.setVisibility(View.VISIBLE);
            affirmUserName.setText(resultEntity.userName);
            affirmUserPhone.setText(resultEntity.userPhone);
            affirmUserLocation.setText(resultEntity.province + " " + resultEntity.city + " " + resultEntity.area
                    + " " + resultEntity.details);
            AddressId = resultEntity.addressId;
        }
    }

}
